package com.mbds.P2Pnetwork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;

public class Client {
	private static final int PORT = 1234;
	private WifiManager wifiManager;
	private static Client singleton;
	
	private Client(WifiManager wifiM) {
		wifiManager = wifiM;
	}
	
	public void init(WifiManager wifiM) {
		if(singleton == null) {
			singleton = new Client(wifiM);
		}
	}
	
	public Client getInstance() {
		return singleton;
	}
	
	private InetAddress getAdresseBroadcast() throws UnknownHostException
	{
	    DhcpInfo dhcp = wifiManager.getDhcpInfo();

	    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
	    byte[] quads = new byte[4];
	    for (int k = 0; k < 4; k++)
	      quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
	    return InetAddress.getByAddress(quads);
	}
	
	public void execute(String... params) {
		new SendTask().execute(params);
	}
	
	private class SendTask extends AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... params) {
			DatagramSocket socket = null;
			try {
				socket = new DatagramSocket(PORT);
				socket.setBroadcast(true);
				InetAddress broadcastAdress = getAdresseBroadcast();

				for (String requete : params) {
					DatagramPacket packet = new DatagramPacket(requete.getBytes(), requete.length(), broadcastAdress, Server.PORT);
					socket.send(packet);
				}



			} catch(SocketException se ) {
				Log.e("Client - Broadcast", se.getMessage());
			} catch (IOException e) {
				Log.e("Client - Broadcast", e.getMessage());
			} finally {
				if(socket != null) {
					socket.close();
				}
			}
			return null;
		}
	}
	
}

